package com.brush.system.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brush.common.constant.UserConstants;
import com.brush.common.core.domain.entity.SysUser;
import com.brush.common.core.domain.resp.AdminUserResp;
import com.brush.common.exception.ServiceException;
import com.brush.common.utils.SecurityUtils;
import com.brush.system.domain.SysUserPost;
import com.brush.system.domain.SysUserRole;
import com.brush.system.domain.req.sysuser.*;
import com.brush.system.domain.resp.sysuser.SysUserResp;
import com.brush.system.mapper.SysUserMapper;
import com.brush.system.mapper.SysUserPostMapper;
import com.brush.system.mapper.SysUserRoleMapper;
import com.brush.system.service.SysUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author 18494
 * @description 针对表【sys_user(用户信息表)】的数据库操作Service实现
 * @createDate 2024-08-19 10:28:03
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public boolean checkDeptExistUser(Long deptId) {
        LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
        query.eq(SysUser::getDeptId, deptId);
        query.eq(SysUser::getDelFlag, UserConstants.NORMAL);
        return this.baseMapper.selectCount(query) > 0;
    }

    /**
     * 分页查询
     * @param req
     * @return
     */
    @Override
    public PageInfo<SysUserResp> paginationQuery(SysUserReq req) {
        return PageHelper.startPage(req.getPageNum(),req.getPageSize())
                .doSelectPageInfo(()->{
                    this.baseMapper.paginationQuery(req);
                });

    }


    @Override
    public List<SysUser> selectUserList(SysUserReq user) {
        return this.baseMapper.selectUserList(user);
    }

    @Override
    public AdminUserResp selectUserByUserName(String userName) {
        return this.baseMapper.selectUserByUserName(userName);
    }

    /**
     * 校验用户是否有数据权限
     * @param userId
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SecurityUtils.isAdmin(userId))  {
            SysUserReq user = new SysUserReq();
            user.setUserId(userId);
            List<SysUser> users = this.selectUserList(user);
            if (Objects.isNull(users))
            {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    @Override
    public AdminUserResp selectUserById(Long userId) {
        return this.baseMapper.selectUserById(userId);
    }

    @Override
    public boolean checkUserNameUnique(String  userName,Long userId) {
        LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
        query.eq(SysUser::getUserName,userName);

        SysUser info =this.getOne(query);
        if (Objects.nonNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


    /**
     * 校验邮箱是否唯一
     * @param email
     * @param userId
     * @return
     */
    @Override
    public boolean checkEmailUnique(String email, Long userId) {
        LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
        query.eq(SysUser::getEmail,email);

        SysUser info =this.getOne(query);
        if (Objects.nonNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertUser(SysUserAddReq user) {
        SysUser sysUser=new SysUser();
        BeanUtils.copyProperties(user,sysUser);
        sysUser.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        sysUser.setUserType("00");

        // 新增用户信息
        boolean result = this.save(sysUser);
        // 新增用户岗位关联
        insertUserPost(user,sysUser.getUserId());
        // 新增用户与角色管理
        insertUserRole(user.getRoleIds(),sysUser.getUserId());
        return result;
    }

    /**
     * 校验用户是否允许操作
     * @param userId
     */
    @Override
    public void checkUserAllowed(Long userId) {
        if (Objects.nonNull(userId) && SecurityUtils.isAdmin(userId))
        {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateUser(SysUserEditReq user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        this.sysUserRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user.getRoleIds(),user.getUserId());
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user,user.getUserId());


        SysUser sysUser=new SysUser();
        BeanUtils.copyProperties(user,sysUser);
        return this.updateById(sysUser) ;
    }

    @Override
    public boolean deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds)
        {
            checkUserAllowed(userId );
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        this.sysUserRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return this.sysUserRoleMapper.deleteUserByIds(userIds)>0;
    }

    /**
     * 用户授权角色
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public boolean insertUserAuth(Long userId, Long[] roleIds)
    {
        this.sysUserRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole( roleIds,userId);
        return true;
    }

    @Override
    public boolean changeStatus(SysUserChangeStatusReq req) {
        SysUser sysUser=new SysUser();
        sysUser.setUserId(req.getUserId());
        sysUser.setStatus(req.getStatus());
        return this.updateById(sysUser);
    }

    /**
     * 重置密码
     * @param req
     * @return
     */
    @Override
    public boolean resetPwd(SysUserChangePwdReq req) {
        SysUser sysUser=this.getById(req.getUserId());
        if (Objects.nonNull(sysUser)){
            String oldPwd=SecurityUtils.encryptPassword(req.getNewPassword());
            if(!oldPwd.equals(sysUser.getPassword())){
                throw new ServiceException("修改密码失败，旧密码错误");
            }

            sysUser.setPassword(SecurityUtils.encryptPassword(req.getNewPassword()));
            return this.updateById(sysUser);
        }
        return false;
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUserAddReq user,Long userId)
    {
        Long[] posts = user.getPostIds();
        if (Objects.nonNull(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(userId);
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole( Long[] roleIds,Long userId)
    {
        if (Objects.nonNull(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            this.sysUserRoleMapper.batchUserRole(list);
        }
    }

    /**
     * userId
     * @param phonenumber
     * @param userId
     * @return
     */
    @Override
    public boolean checkPhoneUnique(String phonenumber, Long userId) {

        LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
        query.eq(SysUser::getPhonenumber,phonenumber);

        SysUser info =this.getOne(query);
        if (Objects.nonNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}




